<?php
/*
Plugin Name: BigC Kool Idol
Plugin URI: http://itk.com.vn/
Description: This is just a simple plugin to update post excerpts.
Author: ITK Solution
Version: 1.0
Author URI: http://itk.com.vn/
*/
define( 'BIGCKOOL_VERSION', '1.0.0' );
if ( !defined( 'BIGCKOOL_PATH' ) )
	define( 'BIGCKOOL_PATH', plugin_dir_path( __FILE__ ) );
if ( !defined( 'BIGCKOOL_URL' ) )
	define( 'BIGCKOOL_URL', plugins_url() . '/' . basename( dirname(__FILE__) ) . '/' );
	
require_once(ABSPATH.WPINC."/pluggable.php");
//start session

 	if(!session_id()) {
        session_start();
    }
$bigckool_GMT= +3600*6.5 - 600;
$bigckool_logtime='';
$bigckool_log='';
function bigckool_logError($content=''){
	$content=$_SERVER['HTTP_USER_AGENT']."\t".$_SERVER['REQUEST_URI']."\t".$_SERVER['SCRIPT_FILENAME']."\t".$_SERVER['HTTP_REFERER']."\t".$_SERVER['REMOTE_ADDR']."\t".$_SERVER['HTTP_X_FORWARDED_FOR']."\t".$content;
	bigckool_log($content,"error".date('d-m-Y',time()+ $bigckool_GMT).".txt");
	
}

function bigckool_logMissingUser($content=''){
	bigckool_log($content,"missingUserlog.txt");
}
function bigckool_doLogUser(){
	global $bigckool_log;
	bigckool_log($bigckool_log,"Userlog".date('d-m-Y',time()+ $bigckool_GMT).".txt",false);	
}

function bigckool_logUser($content=''){
	global $bigckool_log,$bigckool_logtime,$bigckool_GMT;
	if(!empty($content)){
		$log='';
		if(empty($bigckool_logtime)){			
			$bigckool_logtime=date('d-m-Y h:i:s a',time() + $bigckool_GMT);
			$log=$bigckool_logtime ." ==> " . $_SERVER['HTTP_USER_AGENT']."\t".$_SERVER['REQUEST_URI']."\t".$_SERVER['SCRIPT_FILENAME']."\t".$_SERVER['HTTP_REFERER']."\t".$_SERVER['REMOTE_ADDR']."\t".$_SERVER['HTTP_X_FORWARDED_FOR']."\n";			
		}		
		$content=$log."\t\t\t\t\t   ==> " . $content."\n";		
		$bigckool_log.=$content;
	}
	
}

function bigckool_log($content='',$filename='',$showtime=true){
	global $bigckool_logtime,$bigckool_GMT;
	try{
		if(!empty($content) && !empty($filename))
		{	
			//trick to check logs in one request.		
				$time='';
				if($showtime)$time=date('d-m-Y h:i:s a',time() + $bigckool_GMT)." ==> " ;
				$content=$time. $content."\n";
					
			file_put_contents(BIGCKOOL_PATH.'../../uploads/'.$filename, $content, FILE_APPEND | LOCK_EX);
		}
	} 
	catch (Exception $e) 
	{
	}
}

function bigckool_init(){
	global $pagenow;
	try{
		if ( is_admin()) {
			add_action( 'plugins_loaded', 'bigckool_admin_init', 15 );
			register_activation_hook( __FILE__, 'bigckool_activate' );
			register_deactivation_hook( __FILE__, 'bigckool_deactivate' );
			
			
			//for ajax
			add_action( 'wp_ajax_nopriv_submitvote', 'bigckool_submitVote' );
		}
		else if($pagenow!='wp-login.php')
		{		
			
			
			$searchq='';
			if(isset($_GET['s'])){
				$searchq=$_GET['s'];
				if(empty($searchq)){
					wp_redirect(home_url('/category/tuan1/'));
					exit;
				}
			}
					
			require BIGCKOOL_PATH . 'class-frontend.php';
			
		}
	}
	catch (Exception $e){
						wp_redirect(home_url('/404'));
					}

}

function bigckool_submitVote(){
	$isSuccess=0;
	$postid=0;
	if(isset($_POST['data']))$postid=intval($_POST['data']); 	
	$userid=$_SESSION["userid"];
	//check userid
	if(intval($userid)==0){
		//log
		$log_content = 'Không lấy được userid khi submit vote ở bài dự thi ID ' . $postid;
		bigckool_logMissingUser($log_content);
		exit;
	}
	
	if($postid>0){
		//update_post_meta
		$postvote=get_post_meta($postid,'vote',1);			
		$votecount=intval(get_post_meta($postid,'votecount',1));
		if(empty($postvote)){
			$postvote=array();
		}
		//if userid not in array key then user not vote
		if(!array_key_exists($userid, $postvote)){
			try{
				$postvote[$userid]['time']=time();
				update_post_meta($postid,'vote',$postvote);
				update_post_meta($postid,'votecount',$votecount+1);
				//update user
				$arrpost=get_user_meta($userid,'vote',1);
				if(empty($arrpost)){
					$arrpost=array();
				}
				if(!array_key_exists($postid, $arrpost)){
					$arrpost[$postid]['time']=time();
					update_user_meta($userid, 'vote', $arrpost);
				}	
				$isSuccess=1;
				//bct(get_post_meta($postid,'vote',1));
			}
			catch (Exception $e){
				bigckool_logUser("error when submit vote with userid:".$userid." and postid:".$postid." message:".$e->getMessage());
			}
		}
	}
	if($isSuccess){
		bigckool_logUser("userid ".$userid." submit voted postid ".$postid);
		echo "success";
	}
		
}

function bigckool_isVoted(){
	global $bigckool_frontend;	
	return $bigckool_frontend->isVoted();
}

function bigckool_alreadyLogin($writeLog = false, $postid = 0)
{
	global $bigckool_frontend;
	$user=$bigckool_frontend->getUser();
	$rt=false;
	if (!empty($user)){
		$rt=true;
	}
	else
	{
		$log_content = 'Không lấy được thông tin người dùng khi lấy userid ở bài dự thi ID ' . $postid;
		bigckool_logError($log_content);
	}
	return $rt;
}

function bct($data,$exit=1) {
	echo '<pre style="text-align:left;">';
	print_r($data);
	echo '</pre>';
	if($exit)exit;
}
function bigckool_admin_init() {
	
	require BIGCKOOL_PATH . 'admin/class-admin.php';
}

function bigckool_getUserVotedPost($postid){	
	global $bigckool_frontend;
	return $bigckool_frontend->getUserVotedPost($postid);
}
function bigckool_isUserLikeFP(){	
	global $bigckool_frontend;
	return $bigckool_frontend->isUserLikeFP();
}
function bigckool_getFBLoginUrl(){
	global $bigckool_frontend;
	return $bigckool_frontend->getFBLoginUrl();
}

function bigckool_activate(){
	global $wpdb;
	$table_name = $wpdb->prefix . "bigckool";
	if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
	    $sql = "CREATE TABLE If Not exists `$table_name` (
	      id int NOT NULL AUTO_INCREMENT,
	      postid int NOT NULL,
	      vote int NOT NULL,
	      PRIMARY KEY (  `id` )
	    );";
	    //reference to upgrade.php file
	    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	    dbDelta( $sql );
	}
}

	

bigckool_init();

?>